package kr.co.hk.depart;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import kr.co.hk.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;

public class ShinList extends Activity {

	private ArrayList<ShinInfo> arrayList;
	private ArrayAdapter<ShinInfo> arrayAdapter;
	private String title = "";
	private String link = "";
	private String shinCode;
	private String urls;
	private Spinner spn;
	private ProgressDialog progressDialog;
	final private int PROGRESS_DIALOG = 0;
	private boolean pageEx = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shin_list);

		spn = (Spinner) findViewById(R.id.spn);
		ArrayAdapter spAdapter = ArrayAdapter.createFromResource(this,
				R.array.shinname, android.R.layout.simple_spinner_item);
		spAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spn.setAdapter(spAdapter);

		arrayList = new ArrayList<ShinInfo>();
		ListView listView = (ListView) findViewById(R.id.listView);
		arrayAdapter = new ArrayAdapter<ShinInfo>(this,
				android.R.layout.simple_list_item_1, arrayList);
		listView.setAdapter(arrayAdapter);
		spn.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int spPosition, long arg3) {
				arrayList.clear();
				Resources resources = getResources();
				String[] code = resources.getStringArray(R.array.shincode);
				shinCode = code[spPosition];
//				getDateList("http://department.shinsegae.com/store/main/shopping_list.asp?STORE_CD="
//						+ shinCode);
				urls = "http://department.shinsegae.com/store/main/shopping_list.asp?STORE_CD="
						+ shinCode;
				mainProcessing();

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}

		});

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				ShinInfo order = arrayList.get(position);
				String url = order.getShinLink();
				Intent intent = new Intent(ShinList.this, ShinDetail.class);
				intent.putExtra("url", url);
				startActivity(intent);

			}
		});

	}

	private Handler chdHandler = new Handler();

	private void mainProcessing() {
		pageEx = false;
		showDialog(PROGRESS_DIALOG);
		Thread childThread = new Thread(null, dobackgroundThreadProcessing,
				"Backgroud");
		childThread.start();
	}

	private Runnable dobackgroundThreadProcessing = new Runnable() {

		@Override
		public void run() {
			backgroudnThreadProcessing();
		}
	};

	private void backgroudnThreadProcessing() {
		getDateList(urls);
		chdHandler.post(doUpdateGUI);
	}

	private Runnable doUpdateGUI = new Runnable() {

		@Override
		public void run() {
			updateGUI();
		}
	};

	// gui code
	private void updateGUI() {
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		progressDialog.dismiss();
		ShinList.this.removeDialog(PROGRESS_DIALOG);
		if (pageEx) {
			excePro();
		} else {
			arrayAdapter.notifyDataSetChanged();
		}
	}

	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:

			progressDialog = new ProgressDialog(this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progressDialog.setMessage("Now loading..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(false);
			return progressDialog;

		}
		return null;

	}

	public void getDateList(String addr) {
		try {
			URL url = new URL(addr);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			if (conn != null) {
				conn.setConnectTimeout(10000);
				conn.setReadTimeout(10000);
				conn.setUseCaches(false);
				if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					BufferedReader br = new BufferedReader(
							new InputStreamReader(conn.getInputStream(),
									"euc-kr"));
					ArrayList<String> list = new ArrayList<String>();
					String msg = "";
					while ((msg = br.readLine()) != null) {
						list.add(msg.trim() + "\n");
					}

					for (int i = 0; i < list.size(); i++) {

						String line = list.get(i);

						String reStr = line;
						int firstIndex = 0;
						int lastIndex = 0;

						if (line.contains("class=\"title\"")) {
							reStr = list.get(i);

							firstIndex = reStr.indexOf("=\">");
							lastIndex = reStr.indexOf("</a>");
							title = reStr.substring(firstIndex + 3, lastIndex)
									.replace("amp;", "");

						}

						if (line.contains("class=\"title\"")) {
							reStr = list.get(i);

							firstIndex = reStr.indexOf("shopping");
							lastIndex = reStr.indexOf("Key=");
							link = reStr.substring(firstIndex, lastIndex + 4);
							String add = "http://department.shinsegae.com/store/main/";
							link = add + link;
							ShinInfo shin = new ShinInfo(title, link);

							arrayList.add(shin);

						}

					}
					br.close();
				}
				conn.disconnect();

			}
		} catch (Exception ex) {
			pageEx = true;
			ex.printStackTrace();
		}
	}

	private void excePro() {
		toast("페이지 로딩시 오류가  있습니다. \n 네트워크 확인 후 다시 시도 하세요!");
		onBackPressed();
	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

}
